package com.aletto.general_store.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aletto.general_store.R;
import com.aletto.general_store.presenters.GoodsPageTemplate;
import com.aletto.general_store.presenters.SearchHotTemplate;
import com.aletto.general_store.ui.activities.MainActivity;
import com.aletto.general_store.ui.activities.SearchActivity;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.Objects;


/**
 * 主页
 */
public class HomeFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mRefreshLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRefreshLayout = view.findViewById(R.id.refresh_layout);

        view.findViewById(R.id.search)
                .setOnClickListener(v -> startActivity(new Intent(v.getContext(), SearchActivity.class)));

        // 热搜
        RecyclerView searchHotRecycler = view.findViewById(R.id.recycler_hot_search);
        new SearchHotTemplate(searchHotRecycler).execute(getLifecycle());

        // 推荐商品
        new GoodsPageTemplate(mRecyclerView, mRefreshLayout).execute(getLifecycle());

        // 初始化滚动
        initScrollListener();
    }

    private void initScrollListener() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //获得recyclerView的线性布局管理器
                GridLayoutManager manager = (GridLayoutManager) recyclerView.getLayoutManager();

                int firstVisibleItemPosition = Objects.requireNonNull(manager).findFirstVisibleItemPosition();

                // 判断不滑动的情况
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    MainActivity activity = ((MainActivity) getActivity());
                    Objects.requireNonNull(activity).backTop(firstVisibleItemPosition != 0);
                }
            }

        });
    }

    public void backTop() {
        mRecyclerView.smoothScrollToPosition(0);
    }

}
